import Toast from 'tdesign-miniprogram/toast/index';
import {
  baseURL
} from '~/services/request'
import {
  startcomplaint,
  viewSuggestDetail,
  editSuggest
} from '~/services/api/message'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // testFlag: false,
    notFinished: false,
    processStatus: "",
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    isEdit: false,
    showSaveBtn: false,
    kid: '',
    pics: [],
    processPic: [],
    personInfo: {
      title: "",
      content: "",
      agentUserId: '',
      pics: ''
    },
    hideButton: true
  },
  // input 数据绑定
  onInputChange(e) {
    const key = e.currentTarget.dataset.key,
      value = e.detail.value;
    this.setData({
      [key]: value
    })
  },
  editStatus() {
    this.setData({
      isEdit: false,
      showSaveBtn: true
    })
  },


  // 图片上传 
  handleSuccess(e) {
    let self = this;
    let tempOrigin = [];
    const role = wx.getStorageSync('role');
    let picType = e.currentTarget.dataset.type;
    let fileList = e.detail.files;
    this.setData({
      [picType]: [...this.data[picType], ...fileList],
    });
    console.log(fileList, 'fileList')
    //  多图统一上传
    fileList.forEach((el) => {
      wx.uploadFile({
        url: `${baseURL}fileserver/pt/fileserver/action/upload`,
        filePath: el.url,
        name: 'file',
        header: {
          devType: 4,
          userId: role.userId,
          token: role.tokenId,
          appId: "crm_agent",
          authType: "agent"
        },
        success: function (result) {
          if (JSON.parse(result.data).code == 200) {
            const resourceUrl = JSON.parse(result.data).data.urlPath;
            console.log(resourceUrl);
            tempOrigin.push(resourceUrl);
            self.setData({
              "personInfo.pics": [...self.data.personInfo.pics, resourceUrl]
            })
          }
        }
      })
    })
  },
  // 移除图片

  handleRemove(e) {
    const {
      index
    } = e.detail;
    console.log(index)
    let picType = e.currentTarget.dataset.type;
    const picTypeList = this.data[picType];
    this.data[picType].splice(index, 1);
    this.setData({
      [picType]: picTypeList,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    const role = wx.getStorageSync('role');



    if (options.isEdit) {
      this.getDetailData(options)
      this.setData({
        processStatus: options.processStatus
      })
    } else {
      this.setData({
        showSaveBtn: true,
        hideButton: JSON.parse(options.hideButton),
      });
    }
  },
  construstorFile(arr) {
    return arr.map((el) => {
      return {
        url: el,
        type: 'image',
      }
    })
  },

  async getDetailData(options) {
    let {
      code,
      data
    } = await viewSuggestDetail({
      kid: options.kid
    });
    this.setData({
      pics: data.pics ? this.construstorFile(data.pics.split(',')) : [],
      processPic: data.processPic ? this.construstorFile(data.processPic.split(',')) : [],
      personInfo: data,
      kid: options.kid,
      isEdit: options.isEdit,
      hideButton: options.hideButton
    });
  },
  construstorFile(arr) {
    return arr.map((el) => {
      return {
        url: el,
        type: 'image',
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  save() {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    const role = wx.getStorageSync('role');
    console.log(1111)
    if (!this.data.personInfo.content ||
      !this.data.personInfo.title
    ) {
      Toast({
        selector: '#t-toast',
        message: '请完善投诉内容',
        icon: '',
        duration: 1000,
      });
      return;
    };
    let params = {
      ...this.data.personInfo,
      pics: this.data.personInfo.pics && this.data.personInfo.pics.join(','),
      agentUserId: role.userId
    };
    if (options.isEdit) {
      //  编辑
      this.editData(params)
    } else {
      // 新增
      this.saveData(params)
    }
  },
  async editData(params) {
    let {
      code
    } = await editSuggest(params);
    if (code == 200) {
      // wx.reLaunch({
      //   url: '/subpages/pages/suggestList/suggestList',
      // })
      wx.navigateBack({
        delta: -1,
      })
    }
  },

  async saveData(params) {
    let {
      code,
      data
    } = await startcomplaint(params);
    if (code == 200) {
      wx.navigateBack({
        delta: -1,
      })
    }
  },
})